"use strict";

(function($) {
  Drupal.settings.link_crabber = {};
  Drupal.settings.link_crabber.jqxhr = null;

  Drupal.behaviors.link_crabber = {
    attach: function(context) {
      $('.field-name-field-link .form-text').keyup(
        _.debounce(function (event) {
          //use keyup instead keypress because:
          //- keypress will not work on backspace and delete
          //- keypress is called before the character is added to the textfield (at least in google chrome)
          var $this = $(this);
          var search_text = $.trim($this.val());

          var c = String.fromCharCode(event.keyCode);
          var is_word_char = c.match(/\w/);
          var is_backspace_or_delete = (event.keyCode == 8 || event.keyCode == 46);

          if((is_word_char || is_backspace_or_delete)) {
            Drupal.settings.link_crabber.perform_check_link(search_text);
          }
        }, 700)
      );
    }
  }

  Drupal.settings.link_crabber.perform_check_link = function(search_text) {
    if(Drupal.settings.link_crabber.jqxhr && Drupal.settings.link_crabber.jqxhr.readystate != 4) {
      Drupal.settings.link_crabber.jqxhr.abort();
    }

    if(search_text.length > 0) {
      $('.field-name-field-link > .link-crabber-wrapper').html('loading...');
    }
    else {
      $('.field-name-field-link > .link-crabber-wrapper').html('');
      return;
    }

    $('.og-data').val('');

    Drupal.settings.link_crabber.jqxhr = $.ajax({
      type: 'POST',
      url: '/link-helper',
      data: {uri: search_text},
      dataType: 'json'
    })
      .fail(function(jqXHR, textStatus){
        //alert( 'Request failed: ' + textStatus );
      })
      .done(function(data) {
        var tags = data;

        if(!$.isEmptyObject(tags)) {
          $('.field-name-field-link > .link-crabber-wrapper').html(tags.html);
        }
        else {
          $('.field-name-field-link > .link-crabber-wrapper').html('');
        }
      });
  }
})(jQuery);

jQuery( document ).ready(function( $ ) {
  $('.field-name-field-link').append('<div class="link-crabber-wrapper"></div>');
  Drupal.settings.link_crabber.perform_check_link($.trim($('.field-name-field-link .form-text').val()));
});
